/**
 * 
 */
package com.goktech.commons.excel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.goktech.commons.utils.Assert;
import com.goktech.commons.utils.StringUtils;

/**
 * @author 24252
 *
 */
public class ExcelFileTemp {

	private final static Logger logger = LoggerFactory.getLogger(ExcelFileTemp.class);

	private String path = "temp/";
	
	private String prefix = "xlsx";
	
	private String fileId;
	
	public ExcelFileTemp(String path){
		if(!StringUtils.isEmpty(path))
			this.path = path;
	}
	
	private File file;
	public ExcelFileTemp(){
		
	}
	
	public File createNewFile() throws ExcelException, IOException{
		Assert.isNull(fileId, "已有文件存在，无法创建对象文件对象，请先执行clear方法");
		fileId = UUID.randomUUID().toString().replaceAll("-", "")+"."+prefix;
		File file = new File(path+fileId);
		
		if(file.exists()){
			return file;
		}
		File floder = new File(path);
		if(!floder.exists()){
			floder.mkdirs();
		}
		if(!file.createNewFile()){
			fileId = null;
			throw new ExcelException("文件创建失败");
		}
		if(logger.isDebugEnabled())logger.debug("临时文件创建出成功，path:{}",file.getPath());
		return file;
	}
	
	public InputStream createInStream() throws ExcelException, IOException{
		return new FileInputStream(createNewFile());
	}
	//
	public File getFile() throws ExcelException, IOException{
		if(fileId == null && file == null){
			file = createNewFile();
		}
		return file;
	}
	
	//获取文件
	public InputStream getStream() throws ExcelException, IOException{
		return new FileInputStream(getFile());
	}
	
	public OutputStream getOutputStream() throws ExcelException, IOException{
		return new FileOutputStream(getFile());
	}
	
	public boolean clear(){
		if(fileId == null){
			return true;
		}
		File file = new File(path+fileId);
		if(logger.isDebugEnabled())logger.debug("临时文件清除成功，id:{}",this.fileId);
		return file.delete();
	}
	
}
